<?php

/**
 * TomatoCMS
 * 
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2 
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@tomatocms.com so we can send you a copy immediately.
 * 
 * @copyright	Copyright (c) 2009-2010 TIG Corporation (http://www.tig.vn)
 * @license		http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @version 	$Id: PageController.php 4930 2010-08-25 03:38:40Z huuphuoc $
 * @since		2.0.7
 */
class Page_PageController extends Zend_Controller_Action {
    /* ========== Frontend actions ========================================== */

    /**
     * View page details
     *
     * @return void
     */
    public function detailsAction() {
        $request = $this->getRequest();
        $pageId = $request->getParam('id');


        $pageModel = Rabbit_Model_Factory::getInstance()->setModule('page')->getPageModel();

        $page = $pageModel->getById($pageId);
        if (null == $page) {
            throw new Exception('Not found page with id of ' . $pageId);
        }
        $this->view->assign('page', $page);
        /**
         * Add meta keywords
         */
        if ($page->meta_keywords) {
            $this->view->headMeta($page->meta_keywords, "keywords", 'name', array(), 'SET');
        }
        /**
         * Add meta description tag
         */
        if ($page->meta_description) {
            $description = strip_tags($page->meta_description);
            $this->view->headMeta()->setName('description', $description);
        }
        /**
         * Add title
         */
        if ($page->meta_title) {
            $this->view->headTitle($page->meta_title, 'SET');
        } else {
            $this->view->headTitle($page->name, 'SET');
        }
    }

    /* ========== Backend actions =========================================== */

    /**
     * Add new page
     *
     * @return void
     */
    public function addAction() {

        $pageModel = Rabbit_Model_Factory::getInstance()->setModule('page')->getPageModel();
        $request = $this->getRequest();

        /**
         * @since 2.0.8
         */
        $sourceId = $request->getParam('source_id');
        $sourcePage = (null == $sourceId) ? null : $pageModel->getById($sourceId);
        $this->view->assign('sourcePage', $sourcePage);
        $this->view->assign('translatableData', (null == $sourcePage) ? array() : $sourcePage->getProperties());
        $this->view->assign('lang', $request->getParam('lang'));

        if ($request->isPost()) {
            $user = Zend_Auth::getInstance()->getIdentity();

            $page = new Page_Models_Entities_Page(array(
                        'name' => $request->getPost('name'),
                        'slug' => $request->getPost('slug'),
                        'description' => $request->getPost('description'),
                        'content' => $request->getPost('content'),
                        'parent_id' => $request->getPost('parentId'),
                        'num_views' => 0,
                        'created_date' => date('Y-m-d H:i:s'),
                        'modified_date' => null,
                        'user_id' => $user->id,
                        /**
                         * @since 2.0.8
                         */
                        'language' => $request->getPost('language'),
                        /**
                         * Added by TrongHM
                         */
                        'meta_title' => $request->getPost('meta_title'),
                        'meta_description' => $request->getPost('meta_description'),
                        'meta_keywords' => $request->getPost('meta_keywords'),
                    ));
            $pageId = $pageModel->add($page);

            /**
             * @since 2.0.8
             */
            $source = Zend_Json::decode($request->getPost('sourceItem', '{"id": "", "language": ""}'));
            $translationModel = Rabbit_Model_Factory::getInstance()->setModule('core')->getTranslationModel();
            $translationModel->add(new Core_Models_Entities_Translation(array(
                        'item_id' => $pageId,
                        'item_class' => get_class($page),
                        'source_item_id' => ('' == $source['id']) ? $pageId : $source['id'],
                        'language' => $page->language,
                        'source_language' => ('' == $source['language']) ? null : $source['language'],
                    )));

            $this->_helper->getHelper('FlashMessenger')
                    ->addMessage('success:' . $this->view->translate('page_add_success'));
            $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'page_page_add'));
        }
    }

    /**
     * Delete page
     *
     * @return void
     */
    public function deleteAction() {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->getHelper('viewRenderer')->setNoRender();

        $response = 'RESULT_ERROR';
        $request = $this->getRequest();
        if ($request->isPost()) {
            $id = $request->getPost('id');

            $pageModel = Rabbit_Model_Factory::getInstance()->setModule('page')->getPageModel();
            $ids = array();
            if (is_numeric($id)) {
                $ids[] = $id;
            } else {
                $ids = Zend_Json::decode($id);
            }
            foreach ($ids as $pageId) {
                $page = $pageModel->getById($pageId);

                if ($page != null) {
                    $pageModel->delete($page);

                    /**
                     * @since 2.0.8
                     */
                    $translationModel = Rabbit_Model_Factory::getInstance()->setModule('core')->getTranslationModel();
                    $translationModel->delete($pageId, get_class($page));

                    $response = 'RESULT_OK';
                }
            }
        }
        $this->getResponse()->setBody($response);
    }

    /**
     * Edit page
     *
     * @return void
     */
    public function editAction() {
        $request = $this->getRequest();
        $pageModel = Rabbit_Model_Factory::getInstance()->setModule('page')->getPageModel();

        $pageId = $request->getParam('id');
        $page = $pageModel->getById($pageId);

        if (null == $page) {
            throw new Exception('Not found page with id of ' . $pageId);
        }

        /**
         * @since 2.0.8
         */
        $sourcePage = $pageModel->getSource($page);

        $this->view->assign('sourcePage', $sourcePage);
        $this->view->assign('page', $page);

        if ($request->isPost()) {
            $parentId = $request->getPost('parentId');
            $purifier = new HTMLPurifier();

            $page->name = $purifier->purify($request->getPost('name'));
            $page->slug = $request->getPost('slug');
            $page->description = $purifier->purify($request->getPost('description'));
            $page->content = $purifier->purify($request->getPost('content'));
            $page->modified_date = date('Y-m-d H:i:s');

            /**
             * @since 2.0.8
             */
            $page->language = $request->getPost('language', $page->language);

            /**
             * Added by Tronghm
             */
            $page->meta_title = $request->getPost('meta_title');
            $page->meta_description = $request->getPost('meta_description');
            $page->meta_keywords = $request->getPost('meta_keywords');

            /**
             * Get parent page
             */
            $parent = ($page->parent_id) ? $pageModel->getById($page->parent_id) : null;
            if ((null == $parent && 0 == $parentId) || ($parent != null && $parent->page_id == $parentId)) {
                /**
                 * User do NOT change the parent page value
                 */
                $pageModel->update($page);
            } else {
                /**
                 * User changed parent page
                 */
                $page->parent_id = $parentId;
                $pageModel->delete($page);
                $pageId = $pageModel->add($page);
            }

            /**
             * @since 2.0.8
             */
            $source = Zend_Json::decode($request->getPost('sourceItem', '{"id": "", "language": ""}'));
            $translationModel = Rabbit_Model_Factory::getInstance()->setModule('core')->getTranslationModel();
            $translationModel->update(new Core_Models_Entities_Translation(array(
                        'item_id' => $pageId,
                        'item_class' => get_class($page),
                        'source_item_id' => ('' == $source['id']) ? $pageId : $source['id'],
                        'language' => $page->language,
                        'source_language' => ('' == $source['language']) ? null : $source['language'],
                    )));

            $this->_helper->getHelper('FlashMessenger')
                    ->addMessage('success:' . $this->view->translate('page_edit_success'));
            $this->_redirect($this->view->serverUrl() . $this->view->url(array('id' => $pageId), 'page_page_edit'));
        }
    }

    /**
     * List pages
     *
     * @return void
     */
    public function listAction() {
        /**
         * Changed by TrongHM
         */
        $pageModel = Rabbit_Model_Factory::getInstance()->setModule('page')->getPageModel();

        /**
         * @since 2.0.8
         */
        $lang = $this->getRequest()->getParam('lang', Tomato_Config::getConfig()->web->lang);
        $pageModel->setLang($lang);

        $pages = $pageModel->getTree();
        $this->view->assign('pages', $pages);
    }

    /**
     * Update pages' order
     *
     * @return void
     */
    public function orderAction() {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->getHelper('viewRenderer')->setNoRender();

        $response = 'RESULT_ERROR';
        $request = $this->getRequest();
        if ($request->isPost()) {
            $data = $request->getPost('data');
            $data = Zend_Json::decode($data);

            $conn = Tomato_Db_Connection::factory()->getMasterConnection();
            $pageModel = Tomato_Model_Model_Factory::getInstance()->setModule('page')->getPageModel();
            $pageModel->setDbConnection($conn);

            foreach ($data as $page) {
                $pageModel->updateOrder(new Page_Models_Page(array(
                            'page_id' => $page['id'],
                            'parent_id' => $page['parent_id'],
                            'left_id' => $page['left_id'],
                            'right_id' => $page['right_id'],
                        )));
            }

            $response = 'RESULT_OK';
        }
        $this->getResponse()->setBody($response);
    }

}
